#include "ansyc_echo_server.h"

Server::Server(boost::asio::io_context& ioc, short port) :_ioc(ioc),
    _acceptor(ioc, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::any(), port).protocol()){
    _acceptor.bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
    _acceptor.listen();
    StartAccept();
}

void Server::StartAccept() {
    std::shared_ptr<Session> new_session = std::make_shared<Session>(_ioc);
    _acceptor.async_accept(new_session->Socket(),
    std::bind(&Server::HandleAccept, this, new_session, std::placeholders::_1));//值传递session，引用计数＋1
}
void Server::HandleAccept(std::shared_ptr<Session> new_session, const boost::system::error_code& error) {

    std::cout << "session->use_count:" <<new_session.use_count() << std::endl;
    if (!error) {
        //存储到容器
        sessions_.insert(std::make_pair(new_session->GetUuid(),new_session));
        new_session->Start();
    }
    else {
        
    }
    StartAccept();
}

void Server::ClearSession(std::string uuid)
{
    sessions_.erase(uuid);

}


int main(int argc, char const *argv[])
{
    boost::asio::io_context ioc;
    unsigned short port = 10086;
    Server server(ioc,port);
    ioc.run();
    
    return 0;
}
